﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;
using Wicresoft.UnifyShow.Business;
using System.Configuration;

namespace Wicresoft.UnifyShow.Portal
{
    public class BaseController : Controller
    {
        public static string ShowError = ConfigurationManager.AppSettings["ShowError"];
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            //filterContext.Result = View();
            if (ShowError == "True")
            {
                filterContext.ExceptionHandled = false;
            }
            else
            {
                filterContext.Result = Redirect("/Error/ServerError.html");
                filterContext.ExceptionHandled = true;
            }
                
            
        }
        //private string _cookieKey;
        ////in order to SSO,this site must be one of the sub-domain like:
        ////unify.fjyc.com
        ////the parent domain or other sub-domain site will set cookie for the parent domain,
        ////and try to get cookie(UNI_SESS).
        ////if cookie exist,indicate user is authenticated.
        ////otherwise return to own login page
        //protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        //{
        //    base.Initialize(requestContext);

        //    if (_cookieKey == null)
        //    {
        //        //get cookie key
        //        _cookieKey = System.Configuration.ConfigurationManager.AppSettings["SSOCookie"];
        //    }

        //    //not set SSOCookie config,don't try SSO Authentication
        //    if (string.IsNullOrEmpty(_cookieKey)) return;

        //    //try get cookie
        //    var cookie = requestContext.HttpContext.Request.Cookies[_cookieKey];
        //    //SSO cookie exsit
        //    if (cookie != null)
        //    {
        //        //has SSO
        //        CreateUserBySSO(cookie);
        //    }
        //    else
        //    {
        //        string user = CustomLoginUtil.GetUser();
        //        if (string.IsNullOrEmpty(user)) return;
        //        User2 = new CustomPrincipal(
        //            user,//cn
        //            string.Empty,//uid
        //            string.Empty,//dept
        //            null,//logintime
        //            ".local"
        //        );
        //    }
        //}

        //protected override void OnAuthorization(AuthorizationContext filterContext)
        //{
        //    if (User2 != null && User2.Identity != null && User2.Identity.IsAuthenticated)
        //        return;
        //    filterContext.Result = new HttpUnauthorizedResult();
        //}

        //private void CreateUserBySSO(HttpCookie sCookie)
        //{
        //    string[] splits = DecryptSSOCookie(sCookie.Value).Split('&');

        //    User2 = new CustomPrincipal(
        //        splits[0],//cn
        //        splits[1],//uid
        //        splits[2],//dept
        //        DateTime.Parse(splits[3]),//logintime
        //        "SSO"
        //    );
        //}

        //private string DecryptSSOCookie(string org)
        //{
        //    //TODO, mock now, wait for decrypt method
        //    return org;

        //}

        protected void SetRoles(IUser_X user)
        {
            UserSiteIDs = new List<decimal>();
            //if (User != null || User2 != null)
            if (User != null)
            {
                //实际通过数据库动态根据 User 来获取相应地Role;
                //string userName = User != null ? User.Identity.Name : User2.Identity.Name;
                UserLoginID = User.Identity.Name;
                UsersSites = user.GetSiteIDByName(UserLoginID).OrderBy(o => o.ID).ToList();
                //Decimal sitesAllCount = user.GetCountOfTheAllSite();
                User_XModel userM = user.GetUser_XByName(UserLoginID);

                if (userM != null && userM.Disabled == 1) userM = null;

                if (userM == null)
                {
                    UserID = -1;
                    return;
                }

                foreach (var item in UsersSites)
                {
                    UserSiteIDs.Add(item.SiteID);
                }

                UserDisplayName = userM.DisplayName;

                // IsAllAdmin = sitesAllCount == UsersSites.Count ? true : false;
                IsConfigAdmin = userM.IsAdmin == 1 ? true : false;
                UserID = userM.ID;
            }
        }

        public string UserLoginID { get; private set; }
        //public IPrincipal User2 { get; private set; }
        public List<decimal> UserSiteIDs { get; private set; }
        // public bool IsAllAdmin;
        public bool IsConfigAdmin { get; private set; }
        public decimal UserID { get; private set; }
        public string UserDisplayName { get; private set; }
        public List<UserAndSiteModel> UsersSites { get; private set; }

    }
}
